<?php

namespace App\Http\Controllers;


use App\Models\UserInfoModel;
use App\Services\UserInfoJwt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class UserInforController extends Controller
{
    /**
     * 用户授权登录
     */
    public function login(Request $request)
    {
        $code = $request->post('code');
        $nickName = $request->post('nickName');
        $avatar = $request->post('avatar');
        if ($code == '' || $nickName == '' || $avatar == '') {
            return json_encode(['code' => 4001, 'mes' => '参数不能为空', 'data' => []]);
        }
        //获取openid和sessionkey
        //$APPID = config('loginInfo.APPID');
        //$SECRET = config('loginInfo.SECRET');
        //$link = "https://api.weixin.qq.com/sns/jscode2session?appid=$APPID&secret=$SECRET&js_code=$code&grant_type=authorization_code";
        $link = sprintf(config('loginInfo.link'), config('loginInfo.APPID'), config('loginInfo.SECRET'), $code);
        $linkData = file_get_contents($link, true);
        $linkData = json_decode($linkData, true);
        $session_key = $linkData['session_key'];
        $openid = $linkData['openid'];
        //根据openid查询是否有该用户
        $con = (new UserInfoModel())->where('open_id', $openid)->first();
        //没有
        if (!$con) {
            $param = [
                'nickName' => $nickName,
                'avatar' => $avatar,
                'open_id' => $openid,
                'session_key' => $session_key,
                'login_type' => 1,
            ];
            $userAdd = (new UserInfoModel())->create($param);
            if ($userAdd) {
                $jwt = (new UserInfoJwt())->jwtEn($userAdd->id);
                $tel = (new UserInfoModel())->where('id', $userAdd->id)->first();
                if ($tel['tel'] == '') {
                    return json_encode(['code' => 4002, 'mes' => '请绑定手机号', 'data' => $jwt]);
                }
                return json_encode(['code' => 200, 'mes' => '入库', 'data' => $jwt]);
            }
            return json_encode(['code' => 4001, 'mes' => 'error', 'data' => []]);
        }
        $jwt = (new UserInfoJwt())->jwtEn($con->id);
        //判断是否手机号
        if ($con->tel == '') {
            return json_encode(['code' => 4002, 'mes' => '请绑定手机号', 'data' => $jwt]);
        }
        return json_encode(['code' => 200, 'mes' => '不入库', 'data' => $con, 'token' => $jwt]);
    }

    /**
     *手机号登录
     */
    public function getPhoneNumber(Request $request)
    {
        $code = $request->post('code');
        $token = $request->post('token');
        if ($code == '' || $token == '') {
            return json_encode(['code' => 400, 'mes' => '请重新授权', 'data' => []]);
        }
        $access_token = Redis::get('access_token');
        if ($access_token == '') {
            //$APPID = config('loginInfo.APPID');
            //$APPSECRET = config('loginInfo.SECRET');
            //$linkTel = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
            $linkTel = sprintf(config('loginInfo.linkTel'), config('loginInfo.APPID'), config('loginInfo.SECRET'));
            $linkData = file_get_contents($linkTel, true);
            $linkData = json_decode($linkData);
            $access_token = $linkData->access_token;
            Redis::setex('access_token', 7100, $access_token);
            return false;
        }
        $phoneLink = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token";
        $code = [
            'code' => $code,
        ];
        $code = json_encode($code);
        $data = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => "Content-type: application/json",
                'content' => $code,
            ],
        ]);
        $phoneData = file_get_contents($phoneLink, false, $data);
        $phoneData = json_decode($phoneData, true);
        $telPhone = $phoneData['phone_info']['phoneNumber'];

        $jwt = (new UserInfoJwt())->jwtDe($token);

        $id = $jwt['token'];
        //判断手机是否存在
        if ($telPhone) {
            //用手机号查库
            $tel = (new UserInfoModel())->where('id', $id)->update(['tel' => $telPhone]);
            if ($tel) {
                return json_encode(['code' => 200, 'mes' => '手机号授权登陆成功', 'data' => []]);
            }
            return json_encode(['code' => 400, 'mes' => '请重新授权', 'data' => []]);
        }
        return json_encode(['code' => 400, 'mes' => '请重新授权', 'data' => []]);
    }

    /*
     * 查手机号
     */
    public function telFind(Request $request)
    {
        $token = $request->post('token');
        $jwt = (new UserInfoJwt())->jwtDe($token);
        $id = $jwt['token'];
        if ($id) {
            $tel = (new UserInfoModel())->where('id', $id)->first();
            if ($tel == null) {
                return json_encode(['code' => 4001, 'mes' => '请先授权登录', 'data' => $jwt]);
            }
            if ($tel->tel == '') {
                return json_encode(['code' => 4002, 'mes' => '请绑定手机号', 'data' => $jwt]);
            }
            return json_encode(['code' => 200, 'mes' => '登录成功', 'data' => []]);
        }
        return json_encode(['code' => 400, 'mes' => '请重新授权', 'data' => []]);
    }

}